package in.hooray.core.utils;

import java.security.SecureRandom;

public class RandomUniqueId {

	private static SecureRandom randomGenerator = new SecureRandom();

	public static final Integer MAX_WIDTH = 7;

	public static final Integer DEF_WIDTH = 3;

	public static Long getRandomUID() {
		return getRandomUID(DEF_WIDTH);
	}

	public static Long getRandomUID(final Integer width) {
		if (width > MAX_WIDTH) {
			throw new IllegalArgumentException("Expecting to return an unsigned long "
					+ "random integer, it can not be larger than " + MAX_WIDTH + " bytes wide");
		}
		final byte[] bytes = new byte[width];
		randomGenerator.nextBytes(bytes);
		long value = 0;
		for (Integer i = 0; i < bytes.length; i++) {
			value <<= 8;
			value |= bytes[i] & 0xFF;
		}
		return value != 0 ? value : value + 1;
	} 
}
